<script lang="ts" setup>
import type { ConfigModel } from '#/api/system/models';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm, z } from '#/adapter/form';
import { createConfigApi, updateConfigApi } from '#/api/system/config';

defineOptions({
  name: 'ConfigFormModal',
});

const emit = defineEmits<{
  complete: [];
}>();

async function onSubmit(values: Record<string, any>) {
  const input = values as ConfigModel;
  await (input.id ? updateConfigApi(input) : createConfigApi(input));
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        triggerFields: ['code'],
        disabled(values) {
          return !!values.id;
        },
      },
      fieldName: 'code',
      label: '配置代码',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '配置名称',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'value',
      label: '配置值',
      help: 'True/False 表示 boolean 值',
      rules: z.string().trim().min(1),
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '是', value: true },
          { label: '否', value: false },
        ],
      },
      fieldName: 'isFixed',
      label: '内置参数',
      help: '内置参数不能修改和删除',
      defaultValue: false,
      rules: 'required',
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (await formApi.validateAndSubmitForm()) {
      modalApi.close();
      emit('complete');
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values } = modalApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values, false);
        modalApi.setState({ title: '编辑配置' });
      }
    }
  },
  title: '新增配置',
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
